const xss = require('xss')
const {Op} = require('sequelize')

const { UserLogin } = require('../models/login')

// 定义文章模型
class UserDao {

  // 获取文章列表
  static async list(params = {}) {
    const { page = 1, nickname,is_student,mail } = params;
    const pageSize = 10

    // 筛选方式
    let filter = {
      deleted_at: null
    };

    // 筛选方式：存在分类ID
    if (nickname) {
      filter.nickname = nickname;
    }
    if (is_student) {
      filter.is_student = is_student;
    }
    if (mail) {
      filter.mail = mail;
    }

    const user = await UserLogin.scope('iv').findAndCountAll({
      limit: pageSize, //每页10条
      offset: (page - 1) * pageSize,
      where: filter,
      order: [
        ['created_at', 'DESC']
      ],
      // 查询每篇文章下关联的分类
    //   include: [{
    //     model: Category,
    //     as: 'category',
    //     attributes: {
    //       exclude: ['deleted_at', 'updated_at']
    //     }
    //   }]
    });
    return {
      data: user.rows,
      // 分页
      meta: {
        current_page: parseInt(page),
        per_page: 10,
        count: user.count,
        total: user.count,
        total_pages: Math.ceil(user.count / 10),
      }
    };
  }

  // 删除文章
  static async destroy(id) {
    // 检测是否存在文章
    const article = await UserLogin.findOne({
      where: {
        id,
        deleted_at: null
      }
    });
    // 不存在抛出错误
    if (!article) {
      throw new global.errs.NotFound('没有找到相关用户');

    }

    // 软删除文章
    article.destroy()
  }

  // 更新文章
  static async update(id, v) {
    // 查询文章
    const article = await UserLogin.findByPk(id);
    if (!article) {
      throw new global.errs.NotFound('没有找到相关用户');
    }

    // 更新文章
    article.account = v.get('body.account');
    article.pwd = v.get('body.pwd');
    article.keyword = v.get('body.keyword');
    article.is_student = v.get('body.is_student');
    article.number = v.get('body.number');
    article.img = v.get('body.img');
    article.mail = xss(v.get('body.mail'));
    article.work_number = xss(v.get('body.work_number'));
    article.nickname = v.get('body.nickname');
    article.status = v.get('body.status');

    article.save();
  }

  // 文章详情
  static async detail(id) {
    const article = await UserLogin.findOne({
      where: {
        id
      },
      // 查询每篇文章下关联的分类
    //   include: [{
    //     model: Category,
    //     as: 'category',
    //     attributes: {
    //       exclude: ['deleted_at', 'updated_at']
    //     }
    //   }]
    });

    if (!article) {
      throw new global.errs.NotFound('没有找到相关用户');
    }

    return article;
  }

}

module.exports = {
    UserDao
}
